package com.net.showcase.common_socket;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 *
 * Date: 13-10-29
 * Time: 16:47
 */
public class SocketCheck {
    public static void main(String[] args) throws Exception {
        byte[] res = reqNoLen("helloworld".getBytes(), "127.0.0.1", 8080, 10000, 10000);
//        byte[] res = req("helloworld".getBytes(), "10.45.248.140", 9527, 10000, 10000);
        String str = new String(res);
        System.out.println("str = " + str);
    }


    public static byte[] reqNoLen(byte[] data, String ip, int port, int conn_timeout, int read_timeout) throws Exception {
        return req(data, ip, port, conn_timeout, read_timeout, false);
    }

    public static byte[] reqLen(byte[] data, String ip, int port, int conn_timeout, int read_timeout) throws Exception {
        return req(data, ip, port, conn_timeout, read_timeout, true);
    }

    public static byte[] req(byte[] data, String ip, int port, int conn_timeout, int read_timeout, boolean readLen) throws Exception {
        Socket client = null;
        OutputStream dataOutputStream = null;
        DataInputStream dataInputStream = null;
        try {
            client = new Socket();

            client.connect(new InetSocketAddress(ip, Integer.valueOf(port)), Integer.valueOf(conn_timeout));
            client.setSoTimeout(Integer.valueOf(read_timeout));
            dataOutputStream = client.getOutputStream();
            InputStream inputStream = client.getInputStream();
            dataInputStream = new DataInputStream(inputStream);


            byte[] bb = doAction(dataOutputStream, dataInputStream, data, readLen);


            return bb;
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (dataInputStream != null) {
                    dataInputStream.close();
                }
                if (dataOutputStream != null) {
                    dataOutputStream.close();
                }
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                throw e;
            }
        }
    }

    public static byte[] writeShort(int val) {
        byte[] result = new byte[2];
        result[0] = (byte) (val >>> 8);
        result[1] = (byte) (val >>> 0);
        return result;
    }


    private static byte[] doAction(OutputStream req, DataInputStream resp, byte[] data, boolean readLen) throws Exception {
        req.write(writeShort(data.length));
        req.write(data);
        req.flush();
        int len = resp.readUnsignedShort();
        System.out.println("len = " + len);
        return "not imp".getBytes();

    }

  /*  public void postDefaultParam(Map<String, String> param) {
         String InsideMerID = trim(dc.get("InsideMerID"));
         param.put("InsideMerID", InsideMerID);
     }

     private void transRetDate(DataContext dc, Map<String, Object> map) throws Exception {
         String retCode = trim(map.get(PARAM_F39));
         String retMsg = trim(map.get(PARAM_F44));
         dc.put(WirelessDict.RETCODE, retCode);
         dc.put(WirelessDict.RETMSG, retMsg);
         if (!WirelessEC.SUCCESS.equals(retCode)) {
             throw new BusinessException(retCode);
         }
     }*/

     /*@Override
     public void copyErr2Out(String retCode, DataContext dc) {
         if (retCode == null)
             return;
         // ?????????????
         dc.getOut().putAll(dc.getIn());
         dc.getOut().put(XmlMobile.RETCODE, retCode);// ??????
         dc.getOut().put(XmlMobile.RETMSG, trim(dc.get(WirelessDict.RETMSG)));// ???????
     }*/

    //???????????????U?????
    /* public Map<String, String> transformParam(DataContext dc) throws Exception {
         Map<String, String> map = new LinkedHashMap<String, String>();
         *//* for (Map.Entry<String, Serializable> entry : dc.entrySet()) {
            String dc_param_name = trim(entry.getKey());
            String upay_param_name = params.get(PARAM_PREFIX + dc_param_name);
            if (upay_param_name == null || "".equals(upay_param_name)) {
                continue;
            }
            if ("".equals(trim(entry.getValue()))) {
                continue;
            }
            map.put(upay_param_name, trim(entry.getValue()));
        }

        List<Map.Entry<String, String>> mappingList = new ArrayList<Map.Entry<String, String>>(map.entrySet());
        Collections.sort(mappingList, new MacKeyCompared());
        Map<String, String> newMap = new LinkedHashMap<String, String>();
        StringBuilder stringBuilder = new StringBuilder();
        for (Map.Entry<String, String> ele : mappingList) {
            if ("F12_12".equals(ele.getKey())) {
                continue;
            }
            stringBuilder.append(ele.getValue());
            newMap.put(cutSplt(ele.getKey()), ele.getValue());
        }
        newMap.put("F64", stringBuilder.toString());*//*
         return map;
     }*/

    //????????????
    private void setReqContent(DataOutputStream request, short length, byte[] content) throws IOException {


    }

    /* private Map xml2Map(String src) throws Exception {
         String xml_src = src.substring(15);
         PospXmlTopNode topNode = new PospSaxHandler().decode(xml_src.getBytes("GBK"));
         Map map = topNode.getMap_3d();
         return map;
     }*/

//     //??U???????????xml???
//     private byte[] map2Xml(Map upayParam) throws Exception {
//         String charset = System.getProperty("file.encoding");
//         PospXmlTopNode topReq = new PospXmlTopNode(XML_ROOT, charset);
//         topReq.putMap_3d(upayParam);
//         return topReq.toString().getBytes();
//     }


}
